package com.fxkj.cloud.drms.domain.mqtt.service;

import com.fxkj.cloud.drms.domain.mqtt.CommandDomain;
import com.fxkj.cloud.drms.domain.mqtt.CommandAndQuerySender;
import com.fxkj.cloud.drms.domain.commandSettingHistory.CommandSettingHistoryDomain;
import com.fxkj.cloud.drms.domain.commandSettingHistory.service.CommandSettingHistoryDomainService;
import com.fxkj.cloud.drms.domain.mqtt.QueryDomain;
import com.fxkj.common.exception.FxException;
import com.fxkj.common.model.UserInfo;
import com.fxkj.common.utils.UserContext;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * <p>description: </p>
 * @author ww
 * @date 2025/3/25 11:34
 */
@Service
public class SenderServiceImpl implements SenderService {
    private final CommandAndQuerySender commandAndQuerySender;
    private final CommandSettingHistoryDomainService commandSettingHistoryDomainService;

    public SenderServiceImpl(CommandAndQuerySender commandAndQuerySender, CommandSettingHistoryDomainService commandSettingHistoryDomainService) {
        this.commandAndQuerySender = commandAndQuerySender;
        this.commandSettingHistoryDomainService = commandSettingHistoryDomainService;
    }

    @Override
    public void send(CommandDomain commandDomain) {
        //下发消息
        commandAndQuerySender.commandSend(commandDomain);

        //保存历史
        UserInfo userInfo = UserContext.getUserInfo();
        if (Objects.isNull(userInfo)) {
            throw new RuntimeException("用户信息为空");
        }
        commandSettingHistoryDomainService.saveAll(CommandSettingHistoryDomain.create(commandDomain, userInfo));
    }

    @Override
    public void sendBatch(List<CommandDomain> commandDomains) {
        commandAndQuerySender.commandSendBatch(commandDomains);
        UserInfo userInfo = UserContext.getUserInfo();
        if (Objects.isNull(userInfo)) {
            throw new RuntimeException("用户信息为空");
        }
        commandSettingHistoryDomainService.saveAll(commandDomains.stream().map(commandDomain -> CommandSettingHistoryDomain.create(commandDomain, userInfo)).flatMap(Collection::stream).toList());

    }

    @Override
    public void query(QueryDomain queryDomain) {
        commandAndQuerySender.querySend(queryDomain);
    }
}
